package com.fishingwithme.infrastructure;

import com.fishingwithme.domain.user.SpotUser;
import com.fishingwithme.domain.user.UserService;
import com.fishingwithme.domain.user.UsernamePasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 增强的用户详情服务
 * 支持多种登录方式：用户ID、用户名、OpenID
 */
@Service
public class EnhancedUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private UsernamePasswordService usernamePasswordService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 尝试按用户名查找
        SpotUser user = usernamePasswordService.loadUserByUsername(username);
        
        if (user == null) {
            // 尝试按用户ID查找（兼容原有逻辑）
            try {
                Long userId = Long.valueOf(username);
                user = userService.loadUserByUserId(userId);
            } catch (NumberFormatException e) {
                // 不是数字，忽略
            }
        }

        if (user == null) {
            throw new UsernameNotFoundException("User Not Found with username: " + username);
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        if (user.isAdmin()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }

        return new FwmUserDetails(
                user.getUserId(),
                user.getUsername() != null ? user.getUsername() : user.getUserId().toString(),
                user.getPassword() != null ? user.getPassword() : "",
                authorities,
                user.getAvatarUrl(),
                user.getNickname()
        );
    }

    /**
     * 根据用户ID加载用户详情
     */
    public UserDetails loadUserByUserId(Long userId) throws UsernameNotFoundException {
        SpotUser user = userService.loadUserByUserId(userId);
        if (user == null) {
            throw new UsernameNotFoundException("User Not Found with userId: " + userId);
        }

        return createUserDetails(user);
    }

    /**
     * 根据OpenID加载用户详情
     */
    public UserDetails loadUserByOpenId(String openId) throws UsernameNotFoundException {
        SpotUser user = userService.loadUserByOpenId(openId);
        if (user == null) {
            throw new UsernameNotFoundException("User Not Found with openId: " + openId);
        }

        return createUserDetails(user);
    }

    private UserDetails createUserDetails(SpotUser user) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        if (user.isAdmin()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }

        return new FwmUserDetails(
                user.getUserId(),
                user.getUsername() != null ? user.getUsername() : user.getUserId().toString(),
                user.getPassword() != null ? user.getPassword() : "",
                authorities,
                user.getAvatarUrl(),
                user.getNickname()
        );
    }
}